package com.kksoft.android.xiaoliaobaike.fetcher.thread;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tsz.afinal.FinalHttp;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import com.kksoft.android.xiaoliaobaike.Const;
import com.kksoft.android.xiaoliaobaike.model.Article;
import com.kksoft.android.xiaoliaobaike.model.FetchTask;

public class FetchArticleThread implements Runnable {

	private static final String TAG = "FetchArticleThread";

	protected Handler articleHandler;
	FetchTask task;
	int seriesId;

	public FetchArticleThread(Handler articleHandler, FetchTask task) {
		this.articleHandler = articleHandler;
		this.task = task;
		seriesId = task==null?0:task.getSeriesId();
	}

	public void run() {
		Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
		
		List<Article> allArticleList = new ArrayList<Article>();

		String url = task.getUrl();

		// 获取数据
		sendMessage(Const.MSG_ARTICLE_FETCH_START);

		String pageContent = null;
		try {
			pageContent = FinalHttp.get(url);
			if (pageContent == null || pageContent == "" || pageContent.length() == 0) {
				Log.w(TAG, "url not found : " + url);
				sendMessage(Const.MSG_URL_NOT_FOUND, "url not found : " + url);

				return;
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			sendMessage(Const.MSG_ARTICLE_FETCH_ERROR, e.getMessage());
			return;
		}

		sendMessage(Const.MSG_ARTICLE_FETCH_FINISH);

		// 解析数据
		sendMessage(Const.MSG_ARTICLE_ANALYSIS_START);

		List<Article> articleList = null;

		try {
			articleList = parsePage(pageContent);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			sendMessage(Const.MSG_ARTICLE_ANALYSIS_ERROR, e.getMessage());
			return;
		}
		allArticleList.addAll(articleList);

		sendMessage(Const.MSG_ARTICLE_ANALYSIS_FINISH);

		sendMessage(Const.MSG_ARTICLE_LIST, allArticleList);
	}

	private void sendMessage(int what) {
		sendMessage(what, null);
	}

	private void sendMessage(int what, Object obj) {
		Message toSend = articleHandler.obtainMessage(what);
		toSend.arg1 = task.getId();
		toSend.arg2 = task.getPage();
		toSend.obj = obj;
		articleHandler.sendMessage(toSend);
	}

	private List<Article> parsePage(String pageContent) {
		Document doc = Parser.parse(pageContent, Const.BASE_URL);

		Iterator<Element> articleEleList = doc.getElementsByClass("article").iterator();

		List<Article> articleList = new ArrayList<Article>();

		while (articleEleList.hasNext()) {
			Element article = articleEleList.next();

			Element titleEle = article.getElementsByClass("entry-title").get(0).getElementsByTag("a").get(0);

			String title = titleEle.text();
			String articleUrl = titleEle.absUrl("href");

			Integer articleId = null;

			if (articleUrl != null && articleUrl.length() > 0) {
				try {
					articleId = Integer.parseInt(articleUrl.substring(articleUrl.lastIndexOf("/") + 1));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}

			Element imgA = article.getElementsByClass("con-image").get(0).getElementsByClass("thumb").get(0);
			Element[] imgs = imgA.getElementsByTag("img").toArray(new Element[0]);

			String thumbUrl = null;
			String originalUrl = null;
			for (Element img : imgs) {
				if (img.hasClass("thumb")) {
					thumbUrl = img.absUrl("src");

					// originalUrl = thumbUrl.replace("-xbthumb", "");
				}
				// if(img.hasClass("original")) {
				// originalUrl = img.absUrl("src");
				// }
			}

			originalUrl = imgA.getElementsByTag("a").get(0).absUrl("href");

			String pubDate = article.getElementsByClass("addtime").get(0).text().replace("[", "").replace("]", "");
			articleList.add(new Article(null, title, seriesId, articleId, articleUrl, originalUrl, thumbUrl, pubDate, 0, 0));
			// System.out.println("articleId:" + articleId + ",title:" + title
			// + ",articleUrl：" + articleUrl + ",thumbUrl:" + thumbUrl
			// + ",originalUrl:" + originalUrl + ",pubDate:" + pubDate);
		}

		return articleList;
	}

	protected int[] fetchPageRange(int seriesId) {
		int pageStart = 0;
		int pageEnd = 0;
		try {
			String url = Const.getArticleListUrl(seriesId, Integer.MAX_VALUE);
			String pageContent = FinalHttp.get(url);
			Document doc = Parser.parse(pageContent, Const.BASE_URL);

			Elements pagebar = doc.getElementsByClass("pagebar");
			if (pagebar != null && pagebar.size() > 0) {
				Elements pageList = doc.getElementsByClass("pagebar").get(0).getElementsByTag("a");

				for (int i = 0; i < pageList.size(); i++) {
					String text = pageList.get(i).ownText();

					if (text != null && text.trim().length() > 0) {
						try {
							pageStart = Integer.parseInt(text);
							break;
						} catch (NumberFormatException e) {
							e.printStackTrace();
							Log.w(TAG, "err:" + e.getMessage());
						}
					}
				}
				for (int i = pageList.size() - 1; i >= 0; i--) {
					String text = pageList.get(i).ownText();

					if (text != null && text.trim().length() > 0) {
						try {
							pageEnd = Integer.parseInt(text);
							break;
						} catch (NumberFormatException e) {
							e.printStackTrace();
							Log.w(TAG, "err:" + e.getMessage());
						}
					}
				}
			} else {
				pageStart = 1;
				pageEnd = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "err:" + e.getMessage());
		}
		return new int[] { pageStart, pageEnd };
	}

}